package com.wichatbackapi.domain;

import com.alibaba.fastjson2.annotation.JSONField;
import com.wichatbackapi.domain.doa.SysUser;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录用户身份权限
 *
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private SysUser User;

    //存储权限信息
    private List<String> permissions;

    public LoginUser(SysUser User, List<String> permissions) {
        this.User = User;
        this.permissions = permissions;
    }

    //存储SpringSecurity所需要的权限信息的集合
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    /**
     * 用户唯一标识
     */
    //表示该字段不会被序列化
    @JSONField(serialize = false)
    private String token;
    /**
     * 登录时间
     */
    @JSONField(serialize = false)
    private Long loginTime;
    /**
     * 过期时间
     */
    @JSONField(serialize = false)
    private Long expireTime;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return authorities;
        }
        //把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
        authorities = permissions.stream().
                map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {//获取密码
        return User.getPassword();
    }

    @Override
    public String getUsername() {//获取用户名
        return User.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {//是否过期
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {//是否未锁定
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {//是否未过期
        return true;
    }

    @Override
    public boolean isEnabled() {//是否可用
        return true;
    }
}

